package com.weakteam.orderonline.webclient.bean;

import com.weakteam.orderonline.dataresource.general.MainConst;
import com.weakteam.orderonline.dataresource.service.CompositeService;
import com.weakteam.orderonline.dataresource.service.GoodsService;
import com.weakteam.orderonline.dataresource.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.*;

/**
 * @author Nail
 */
public class ImageStore implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(ImageStore.class);

    @Autowired(required=true)
    Properties mainDataProperties;

    @Autowired
    CompositeService compositeService;

    private String contentPath;
    private String imagePath;
    private String mobileImagePath;

    private File imageFolder;
    private File mobileImageFolder;

    private FilenameFilter imageFilter;

    public ImageStore() {
        imageFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".jpg");
            }
        };
    }

    public String getAllEnabledPictureFilesList() {
        HashSet<String> set = compositeService.getAllEnabledPictureFilesList();
        StringBuilder json = new StringBuilder();
        if (set.size() > 0) {
            json.append("[\"");
            for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
                String fileName = it.next();
                json.append(fileName);
                if (it.hasNext()) json.append("\",\"");
            }
            json.append("\"]");
        } else {
            json.append("[]");
        }
        return json.toString();
    }

    public File getImageFile(String name, boolean forMobile) {
        if (forMobile) {
            return new File(this.mobileImageFolder, name);
        } else {
            return new File(this.imageFolder, name);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String CATALINA_HOME = System.getProperty("catalina.home");
        this.contentPath = CATALINA_HOME + "/" + this.mainDataProperties.getProperty("contentPath");
        this.imagePath = this.mainDataProperties.getProperty("imagePath");
        this.mobileImagePath = this.mainDataProperties.getProperty("mobileImagePath");
        this.imageFolder = new File(contentPath, imagePath);
        this.mobileImageFolder = new File(contentPath, mobileImagePath);
    }

}